package xyz.xtgl.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import xyz.xtgl.config.helper.CustomTokenExceptionEntryPoint;
import xyz.xtgl.oahth2.config.constant.GlobalConstant;

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;

    @Bean
    public CustomTokenExceptionEntryPoint customTokenExceptionEntryPoint(){
        return new CustomTokenExceptionEntryPoint();
    }


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources
                .authenticationEntryPoint(customTokenExceptionEntryPoint())
                .resourceId(GlobalConstant.XTGL_WEB_MERCHANT_RESOURCES_ID)//资源 id
                .tokenStore(tokenStore)
                .stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest()
                    .access("#oauth2.hasScope('"+ GlobalConstant.XTGL_WEB_CASHIER_SCOPE +"')")
                .and().csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
